package com.zisuyi.uilibrary.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import com.weilele.mvvm.base.helper.ILifecycleObserver
import com.weilele.mvvm.base.helper.data
import com.weilele.mvvm.utils.activity.dip
import com.weilele.mvvm.utils.activity.getActivity
import com.weilele.mvvm.utils.activity.setIcon
import com.weilele.mvvm.utils.insetSplitStr
import com.zisuyi.game.sdk.utils.UserData
import com.zisuyi.uilibrary.R
import com.zisuyi.uilibrary.base.BaseUiViewModel

class AmountTextView : FontTextView, ILifecycleObserver {

    private var isResume = false
    private var numAnim: ValueAnimator? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context,
            attrs,
            defStyleAttr
    ) {
        getActivity()?.lifecycle?.addObserver(this)
    }
    init {
        textSize = 18f
        setTextColor(Color.parseColor("#FFEC23FF"))
        setIcon(R.drawable.diamond, drawablePaddingDip = 4)
        setPadding(dip(8), 0, dip(13), 0)
        gravity = Gravity.CENTER
        setBackgroundResource(R.drawable.bg_coin)
    }


    private val listener = ValueAnimator.AnimatorUpdateListener { p0 ->
        val currentNum = p0.animatedValue as Int
        text = currentNum.toString()
    }

    fun setNumber(num: Long?) {
        num ?: return
        val oldNum = text.toString().replace(",","").toInt()
        val newNum = num.toInt()
        if (oldNum == newNum) {
            return
        }
        if (isResume) {
            numAnim?.cancel()
            numAnim = ValueAnimator.ofInt(oldNum, newNum)
            numAnim?.duration = 400
            numAnim?.addUpdateListener(listener)
            numAnim?.start()
        } else {
            text = num.toString()
        }
    }

    override fun onResume() {
        isResume = true
    }

    override fun onPause() {
        isResume = false
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        BaseUiViewModel.amountViews.remove(this)
        numAnim?.cancel()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        val diamond = UserData.userAssetsData.data?.diamond?.toString().insetSplitStr()
        text = if (diamond.isBlank()) {
            "0"
        } else {
            diamond
        }
        BaseUiViewModel.amountViews.add(this)
    }
}